<?php
namespace app\api\server\payment;
use app\command\Order;
use app\logic\model\MintTransferLogModel;

use app\api\model\OpusModel;
use app\api\model\OpusNumberModel;
use app\api\model\UserModel;
use think\Request;
use think\facade\Db;
use think\facade\Log;
use app\Common as appCommon;
use app\api\model\Auction;
use app\api\model\order\OrderAuction;
/**
 * @Propuse 此接口不进行验证是否登陆 
 * @desc 支付回调方法
 */
class NotifyAuction{
	protected $request;
	protected $addSettingParam=array();
	protected static $s_model;
	protected static $s_model_order;
    use Nft;
	public function __construct()
    {
    	self::$s_model=new Auction();
    	self::$s_model_order=new OrderAuction();
    }
    
	/**
	 * @Purpose 拍卖金支付成功
	 */
	public function payment($_param){
		//开启事务
    	Db::startTrans();
    	Log::record("=============================支付回调开始============================");
    	//1处理corepay状态防止一个订单多次执行回调方法
    	$_up_flag=$this->updateCorePay($_param);
    	if($_up_flag==false){
    		Db::rollback();
    		return false;
    	}
    	//2.处理保证金状态和数据等
    	$_updata_order_flag=$this->updateAuctionMargin($_param);
    	if($_updata_order_flag==false){
    		Db::rollback();
    		return false;
    	}
    	Db::commit();
    	Log::record("=============================支付回调正常结束============================");
    	return true;
	}
	/**
	 * @title 拍卖订单支付成功回调
	 */
	public function paymentOrder($_param){
		//开启事务
    	Db::startTrans();
    	Log::record("=============================支付回调开始============================");
    	//1处理corepay状态防止一个订单多次执行回调方法
    	$_up_flag=$this->updateCorePay($_param);
    	if($_up_flag==false){
    		Db::rollback();
    		return false;
    	}
    	//2.处理保证金状态和数据等
    	$_updata_order_flag=$this->updateAuctionOrder($_param);
    	if($_updata_order_flag==false){
    		Db::rollback();
    		return false;
    	}
    	Db::commit();
    	Log::record("=============================支付回调正常结束============================");
    	return true;
	}
	
	public function updateAuctionOrder($param){
    	$id=$param['order_id'];
    	$_order=self::$s_model_order->findOrder(["id"=>$id],"*");
    	if($_order['status']==1){
    		Log::record(__function__.":".__line__."\r\n"."支付回调已完成不需要继续回调");
    		return false;
    	}
    	//1.更新状态并记录当前支付参数
    	$_order_up=[
    		'transaction_id'=>$param['transaction_id'],
    		'pay_time'=>time(),
    		'pay_type'=>$this->pay_type[$param['type']],
    		'status'=>1,
    	];
    	$_order_update_flag=self::$s_model_order->updateOrder($_order_up,$_where=['id'=>$id]);
    	if(!$_order_update_flag){
    		Log::record(__function__.":".__line__."\r\n"."更新订单状态失败");
    		Log::record(__function__.":".__line__."\r\n"."up:".json_encode($_order_up)."|where:".json_encode($_where));
    		return false;
    	}
    	//2.生成日志
    	$_order_operation=[
    		'order_id'=>$id,
    		'type'=>1,
    		'operation_name'=>'系统',
    		'create_time'=>time()
    	];
    	if(!($_order_id=self::$s_model_order->insertOrderLog($_order_operation))){
			Log::record(__function__.":".__line__."\r\n"."添加支付成功记录日志失败");
    		Log::record(__function__.":".__line__."\r\n"."insert:".json_encode($_order_operation));
			return false;
		}
    	//转移NFT(接口)和转移作品(自身系统)
        $opusNumberModel= new OpusNumberModel();
    	//获取拍卖品信息
        $auctionOpus=Db::name('auction_opus')->where('id',$_order['auction_opus_id'])->find();
        //转移作品
        $opusNumberModel->modifyOwner($_order['user_id'],$auctionOpus['opus_number_id']);
        /**获取转移NFT信息**/
        $mintTransferLog['transfer_opus_number_id']=$auctionOpus['opus_number_id'];
        //买家信息
        $buyer=(new UserModel())->getFindByid($_order['user_id']);
        //作品信息(用于获取卖家信息)
        $opus=(new OpusModel())->getFindByid($auctionOpus['opus_id']);
        //卖家信息（作家信息）
        $seller=(new UserModel())->getFindByid($opus['writer_id']);
        /**转移nft开始**/
        $transferRes=$this->transfer($seller['nft'],$buyer['nft'],[$auctionOpus['opus_number_id']]);
        $mintTransferLog['transfer_message']=$transferRes['message'];

        $mintTransferLogModel= new MintTransferLogModel();
        $mintTransferLogModel->save($mintTransferLog);
    	return true;
    
	}
    public $pay_type=[
    	'0'=>'0',//微信小程序
    	'1'=>'1',//微信公众号
    ];
    
	
	public function updateAuctionMargin($param){
    	$id=$param['order_id'];
    	$_order=self::$s_model->findMarginStatus(["id"=>$id],"*");
    	if($_order['status']==1){
    		Log::record(__function__.":".__line__."\r\n"."支付回调已完成不需要继续回调");
    		return false;
    	}
    	//1.更新状态并记录当前支付参数
    	$_order_up=[
    		'transaction_id'=>$param['transaction_id'],
    		'pay_time'=>time(),
    		'pay_type'=>$this->pay_type[$param['type']],
    		'status'=>1,
    	];
    	$_order_update_flag=self::$s_model->updateMargin($_order_up,$_where=['id'=>$id]);
    	if(!$_order_update_flag){
    		Log::record(__function__.":".__line__."\r\n"."更新订单状态失败");
    		Log::record(__function__.":".__line__."\r\n"."up:".json_encode($_order_up)."|where:".json_encode($_where));
    		return false;
    	}
    	return true;
    }
    
	
	public function updateCorePay($param){
    	$id=$param['id'];
    	if($param['status']==1){
    		$this->error="支付回调失败。当前支付已完成不需要继续回调";
    		Log::record(__function__.":".__line__."\r\n"."支付回调失败。当前支付已完成不需要继续回调");
    		return false;
    	}
    	Log::record(__function__.":".__line__."\r\n"."支付回调更新corePay状态");
    	$_updata_flag=self::$s_model->upAuctionCorePay($_up=['status'=>1,'up_time'=>time()],$_where=['id'=>$id]);
    	Log::record(__function__.":".__line__."\r\n"."支付回调更新corePay状态:".$_updata_flag);
    	Log::record(__function__.":".__line__."\r\n"."up:".json_encode($_up)."|where:".json_encode($_where));
    	if($_updata_flag==false){
    		$this->error="支付回调更新corePay状态:";
    		return false;
    	}
    	return true;
	}
	
}
?>